#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from models import Server,xmlrpc_api
from models import NewserverForms
import json
import simplejson
from django.views.decorators.csrf import csrf_exempt
import os, random, string
import xmlrpclib

def login_xmlrpc(ip,port):
	server = xmlrpclib.Server("http://%s:%d/cobbler_api" %(ip,port))
	return server

def xmlrpc_get_profile(server):
	return server.get_profiles()

def xmlrpc_new_system(xmlrpc_id,name,profile,mac):
	try:
		cobbler_server = xmlrpc_api.objects.get(id=xmlrpc_id)
		server = login_xmlrpc(cobbler_server.ip,cobbler_server.port)
		token = server.login('cobbler','king+5688')
		system_id = server.new_system(token)
		server.modify_system(system_id,'name',str(name),token)
		server.modify_system(system_id,"profile",str(profile),token)
		server.modify_system(system_id,'modify_interface',{ "macaddress-eth0" : str(mac) },token)
		server.modify_system(system_id,"ks_meta", "mac=%s" % str(mac), token)
		server.save_system(system_id, token)
		server.sync(token)
		return True
	except Exception, e:
		return False

def xmlrpc_del_system(xmlrpc_id,systems_name):
	try:
		cobbler_server = xmlrpc_api.objects.get(id=xmlrpc_id)
		server = login_xmlrpc(cobbler_server.ip,cobbler_server.port)
		token = server.login('cobbler','king+5688')
		server.remove_system(systems_name,token)
		return True
	except Exception, e:
		return False

def create_password():
	length = 24
	chars = string.ascii_letters + string.digits + '!@#$%^&*()'
	random.seed = (os.urandom(1024))
	password = ''.join(random.choice(chars) for i in range(length))
	return password

def home(request):
#    return redirect("/server_map/map/")
	if request.method == 'POST':
		form = NewserverForms(request.POST)
		if form.is_valid():
			insert = form.cleaned_data
			password = create_password()
			result = xmlrpc_new_system(insert['cobbler_server_id'],insert['mac'],insert['profile'],insert['mac'])
			if result:
				p = Server(eth0=insert['eth0'],eth1=insert['eth1'],hostname=insert['hostname'],password=password,mac=insert["mac"],xmlrpc_id=insert['cobbler_server_id'],profile=insert['profile'])
				p.save()
			else:
				HttpResponse("Create cobbler objects Failed")
	servers = Server.objects.all().filter(state_code=0)
	cobbler = xmlrpc_api.objects.all()
	return render_to_response("home.html",{"servers": servers,"cobbler_server":cobbler},context_instance=RequestContext(request))

def task_finish(request):
	servers = Server.objects.all().exclude(state_code=0)
	return render_to_response("task_finish.html",{"servers": servers},context_instance=RequestContext(request))

def delete(request):
	if not request.GET:
		return HttpResponse("404")

	id = request.GET["id"]
	if request.GET["type"] == "wait_task":
		if not id:
			return HttpResponse(u"不存在此条目")
		task_info = Server.objects.get(id=id)
		xmlrpc_del_system(task_info.xmlrpc_id,task_info.mac)
		Server.objects.filter(id=id).delete()
		return redirect("/")

def edit(request):
	if request.method == "GET":
		id = request.GET["id"]
		if not id:
			return HttpResponse(u"不存在此条目")
		servers = Server.objects.get(id=id)
		cobbler = xmlrpc_api.objects.all()
		return render_to_response("edit.html",{"servers": servers,"cobbler_server": cobbler},context_instance=RequestContext(request))
	elif request.method == "POST":
		form = NewserverForms(request.POST)
		if form.is_valid():
			id = request.POST["id"]
			update = form.cleaned_data
			print update['password']
			try:
				Server.objects.filter(id=id).update(eth0=update['eth0'],eth1=update['eth1'],hostname=update['hostname'],password=update['password'],mac=update['mac'],xmlrpc_id=update['cobbler_server_id'],profile=update['profile'])
				return redirect("/")
			except Exception, e:
				return HttpResponse(e)

def reset(request):
	if request.method == "GET":
		id = request.GET["id"]
		try:
			Server.objects.filter(id=id).update(state_code=0,message=u"等待")
			cobbler_server = Server.objects.get(id=id)
			result = xmlrpc_new_system(cobbler_server.xmlrpc_id,cobbler_server.mac,cobbler_server.profile,cobbler_server.mac)
			return redirect("/kis_cobbler/task_finish/")
		except Exception, e:
			return HttpResponse(e)

@csrf_exempt
def get_profile(request):
	if request.method == 'POST':
		id = request.POST["cobbler_id"]
		cobbler_server = xmlrpc_api.objects.get(id=id)
		server = login_xmlrpc(cobbler_server.ip,cobbler_server.port)
		result = xmlrpc_get_profile(server)
		html = ""
		for i in result:
			html += "<option value=%s>%s</option>" %(i["name"],i["name"])
		print html
		return HttpResponse(html)

@csrf_exempt
def gettaskinfo(request):
	servers = set()
	if request.method == 'POST':
		result = Server.objects.all().filter(id=request.POST["taskid"])
		for _severs in result:
			servers.add(_servers)
		print servers
		return HttpResponse(servers)

@csrf_exempt
def kis_cobbler_api_getdata(request):
	if request.method == 'POST':
		input = json.loads(request.body)
		result = Server.objects.get(mac=input['mac'],state_code=0)
		result = "result|ok\teth0|%s\teth1|%s\thostname|%s\tpassword|%s\n" %(result.eth0,result.eth1,result.hostname,result.password)
		return HttpResponse(result)

@csrf_exempt
def kis_cobbler_api_postresult(request):
	if request.method == 'POST':
		input = json.loads(request.body)
		if input['result'] == "0":
			state_code = 1
		else:
			state_code = 2
		Server.objects.filter(mac=input['mac']).update(state_code=state_code,state="configuration completed",message=input['message'])
		task_info = Server.objects.get(mac=input['mac'])
		result = xmlrpc_del_system(task_info.xmlrpc_id,task_info.mac)
		if result:
			return HttpResponse("ok")
		else:
			return HttpResponse("Failed")